package org.jeecg.modules.doctor;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterRecord;
import org.jeecg.common.modules.doctor.service.IDoctorRegisterHospitalService;
import org.jeecg.common.modules.doctor.service.IDoctorRegisterRecordService;
import org.jeecg.common.modules.doctor.service.IDoctorService;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterRecordListVo;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterRecordSysListVo;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterRecordSysSettleVo;
import org.jeecg.common.modules.doctor.vo.DoctorWholeVo;
import org.jeecg.common.modules.patient.service.IPatientService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.util.DySmsEnum;
import org.jeecg.common.util.enums.RegisterEnum;
import org.jeecg.modules.data.response.DoctorDeitVo;
import org.jeecg.modules.data.service.DySendMsg;
import org.jeecg.modules.data.service.PageReturn;
import org.jeecg.modules.data.service.RegisterService;
import org.jeecg.modules.system.vo.ResultVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
* @Description: doctor_register_account
* @Author: jeecg-boot
* @Date:   2020-12-23
* @Version: V1.0
*/
@Api(tags="doctorRegisterAccount")
@RestController
@RequestMapping("/doctorRegisterAccount/doctorRegisterAccount")
@Slf4j
public class DoctorRegisterAccountController extends JeecgController<DoctorRegisterRecord, IDoctorRegisterRecordService> {
   @Autowired
   private IDoctorRegisterRecordService doctorRegisterRecordService;
   @Autowired
   private IPatientService patientService;
   @Autowired
   private IDoctorService doctorService;
   @Resource
   private IDoctorRegisterHospitalService doctorRegisterHospitalService;


   /**
    * 分页列表查询
    *
    * @param doctorRegisterRecord
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @AutoLog(value = "doctorRegisterAccount-分页列表查询")
   @ApiOperation(value="doctorRegisterAccount-分页列表查询", notes="doctorRegisterAccount-分页列表查询")
   @GetMapping(value = "/list")
   public Result<?> queryPageList(DoctorRegisterRecord doctorRegisterRecord,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                  HttpServletRequest req) {
       //分页数据开始的记录数
       int dataStart = (pageNo - 1) * pageSize;

       Integer status = null;
       //（1）先查询所有信息
       String doctorName = req.getParameter("doctorName");
       String patientName = req.getParameter("patientName");
       String statusStr = req.getParameter("status");
       String visitTime = req.getParameter("visitTime");
       if(Objects.nonNull(statusStr)){
           status = Integer.valueOf(statusStr);
       }

       List<DoctorRegisterRecordSysListVo> recordVos = doctorRegisterRecordService.getRegisterRecordSysList(doctorName,patientName,visitTime,status,dataStart,pageSize);

       //（2）获取总条数
       Integer count = doctorRegisterRecordService.getRegisterRecordSysCount(doctorName,patientName,visitTime,status);

       //（3）组织分页的返回数据
       PageReturn pageReturn = new PageReturn();
       ResultVo vo = pageReturn.initResultVo(recordVos,count,pageNo,pageSize);
       return Result.ok(vo);
   }

   /**
    *   添加
    *
    * @param doctorRegisterRecord
    * @return
    */
   @AutoLog(value = "doctorRegisterAccount-添加")
   @ApiOperation(value="doctorRegisterAccount-添加", notes="doctorRegisterAccount-添加")
   @PostMapping(value = "/add")
   public Result<?> add(@RequestBody DoctorRegisterRecord doctorRegisterRecord) {
       doctorRegisterRecordService.save(doctorRegisterRecord);
       return Result.ok("添加成功！");
   }

   /**
    *  编辑
    *
    * @param doctorRegisterRecord
    * @return
    */
   @AutoLog(value = "doctorRegisterAccount-编辑")
   @ApiOperation(value="doctorRegisterAccount-编辑", notes="doctorRegisterAccount-编辑")
   @PutMapping(value = "/edit")
   public Result<?> edit(@RequestBody DoctorRegisterRecord doctorRegisterRecord) {
       doctorRegisterRecordService.updateById(doctorRegisterRecord);
       return Result.ok("编辑成功!");
   }

    /**
     * 详情
     */
    @GetMapping(value = "/details")
    public Result<?> details(@RequestParam(name="recordId") String recordId){

        DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(recordId);
        if(Objects.isNull(doctorRegisterRecord)){
            return Result.error("该记录不存在");
        }
        //返回值定义 DoctorRegisterRecordListVo             //服务类 doctorRegisterRecordService   //getRecordById 定义
        DoctorRegisterRecordListVo registerRecord = doctorRegisterRecordService.getRecordById(recordId);  //记录id  recordId
        //定义组合  DoctorResVo       // 重新定义   new DoctorResVo
        DoctorDeitVo recordListResVo = new DoctorDeitVo();


        //进行对象之间的属性赋值  BeanUtils.copyProperties
        BeanUtils.copyProperties(registerRecord,recordListResVo);

        //单独查询设置值（上面没有值到这里查后赋值）
        //压缩后的赋值  doctorRegisterHospitalService.getById(recordListResVo.getRegisterHospitalId()).getName()
        recordListResVo.setRegisterHospitalName(doctorRegisterHospitalService.getById(recordListResVo.getRegisterHospitalId()).getName()); //就诊医院
        recordListResVo.setVisitTime(RegisterService.subStr(recordListResVo.getVisitTime(),5)); //就诊日期

        //获取医生信息
        DoctorWholeVo doctor = doctorService.doctorWhole(recordListResVo.getDoctorId());

        //多赋值doctor.getName()  doctor.getTitle()  doctor.getDepartmentName()
        recordListResVo.setDoctorName(doctor.getName());
        recordListResVo.setTitle(doctor.getTitle());
        recordListResVo.setDepartmentName(doctor.getDepartmentName());
        recordListResVo.setFailReason(doctorRegisterRecord.getFailReason());
        return Result.ok(recordListResVo);
    }
   /**
    *   通过id删除
    *
    * @param id
    * @return
    */
   @AutoLog(value = "doctorRegisterAccount-通过id删除")
   @ApiOperation(value="doctorRegisterAccount-通过id删除", notes="doctorRegisterAccount-通过id删除")
   @DeleteMapping(value = "/delete")
   public Result<?> delete(@RequestParam(name="id",required=true) String id) {
       doctorRegisterRecordService.removeById(id);
       return Result.ok("删除成功!");
   }

   /**
    *  批量删除
    *
    * @param ids
    * @return
    */
   @AutoLog(value = "doctorRegisterAccount-批量删除")
   @ApiOperation(value="doctorRegisterAccount-批量删除", notes="doctorRegisterAccount-批量删除")
   @DeleteMapping(value = "/deleteBatch")
   public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
       this.doctorRegisterRecordService.removeByIds(Arrays.asList(ids.split(",")));
       return Result.ok("批量删除成功!");
   }

   /**
    * 通过id查询
    *
    * @param id
    * @return
    */
   @AutoLog(value = "doctorRegisterAccount-通过id查询")
   @ApiOperation(value="doctorRegisterAccount-通过id查询", notes="doctorRegisterAccount-通过id查询")
   @GetMapping(value = "/queryById")
   public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
       DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getById(id);
       if(doctorRegisterRecord==null) {
           return Result.error("未找到对应数据");
       }
       return Result.ok(doctorRegisterRecord);
   }

   /**
   * 导出excel
   *
   * @param request
   * @param doctorRegisterRecord
   */
   @RequestMapping(value = "/exportXls")
   public ModelAndView exportXls(HttpServletRequest request, DoctorRegisterRecord doctorRegisterRecord) {
       return super.exportXls(request, doctorRegisterRecord, DoctorRegisterRecord.class, "doctorRegisterAccount");
   }

   /**
     * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
   @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
   public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       return super.importExcel(request, response, DoctorRegisterRecord.class);
   }


   // =================++++++++++++++++++ 短信通知 ++++++++++++++++++++===================

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";

    //  此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
    static String accessKeyId = "LTAI4FmjinJVdYBiTqNhsXZd";
    static String accessKeySecret="pRGUqC44n9PG9kGdbYNgP3xCu2p7RE";

    public static boolean sendSms(String phone, JSONObject templateParamJson, DySmsEnum dySmsEnum) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //验证json参数
        validateParam(templateParamJson, dySmsEnum);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(dySmsEnum.getSignName());
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(dySmsEnum.getTemplateCode());
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(templateParamJson.toJSONString());

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");

        boolean result = false;

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        log.info("短信接口返回的数据----------------");
        log.info("{Code:" + sendSmsResponse.getCode() + ",Message:" + sendSmsResponse.getMessage() + ",RequestId:" + sendSmsResponse.getRequestId() + ",BizId:" + sendSmsResponse.getBizId() + "}");
        if ("OK".equals(sendSmsResponse.getCode())) {
            result = true;
        }
        return result;

    }

    private static void validateParam(JSONObject templateParamJson, DySmsEnum dySmsEnum) {
        String keys = dySmsEnum.getKeys();
        if (StringUtils.isBlank(keys)){
            return;
        }
        String[] keyArr = keys.split(",");
        for (String item : keyArr) {
            if (!templateParamJson.containsKey(item)) {
                throw new RuntimeException("模板缺少参数：" + item);
            }
        }
    }
}
